<?php
/**
 * Controller to manage product template attributes in admin area
 * 
 * @author Konstantin Shamko <konstantin.shamko@gmail.com> 
 * @version 0.0.1
 * @copyright  Copyright (c) 2009 Konstantin Shamko
 * @package Products Module
 * @license  New BSD License
 * 
 */
class admin_ProducttemplatesattrController extends Bel_Controller_Aed  {

	/**
	 * Initialization. Creates left menu for index & form action
	 * Redifines _form_action, _index_action and _delete_action URLs by adding 
	 * product_template_id param
	 * 
	 */	
	function init() {
		$this->_model = new Models_ProductTemplates_Attributes();
		$this->_formname = 'product_template_attributes_form';
		parent::init ();
		
		if($this->_request->getParam('product_template_id') && $this->_request->getActionName()!='modify'){
			$this->_model->setTemplate($this->_request->getParam('product_template_id'));
			Helpers_Products_Admin_TemplatesMenu::leftMenu($this->_request->getParam('product_template_id'));
		}
		
		$this->_form_action = $this->_form_action.'/product_template_id/'.$this->_request->getParam('product_template_id');
		$this->_index_action = $this->_index_action.'/product_template_id/'.$this->_request->getParam('product_template_id');
		$this->_delete_action = $this->_delete_action.'/product_template_id/'.$this->_request->getParam('product_template_id');
		
	}
	
	/**
	 * Populates attributes dropdown with available attributes.
	 * Populates product_template_id field with value from request
	 *
	 * @param Bel_Forms_Builder $form
	 */
	protected function _prepareForm(Bel_Forms_Builder $form){
		$oAttr = new Models_ProductAttributes();
		$attributes = $oAttr->getAll(null,'attribute_name');			
		if(count($attributes)){
			$options = array();
			foreach ($attributes as $attribute){
				$options[$attribute->attribute_id] = $attribute->attribute_name;	
			}
			$form->addSubElement('attribute_id','options',$options);		
			$form->addAttributes('product_template_id',array('value'=>$this->_request->getParam('product_template_id')));
		}else{
			$this->_messages->setMessage('Attributes not exixst. Add few first!', 'error');
			$this->_redirect($this->_index_action);
			
		}
		
	}
	
	/**
	 * Clears product cahe after modify action
	 *
	 */
	protected function _afterModify(){
		Helpers_Products_Cache::cleanProductCacheByTemplate($this->_request->getParam('product_template_id'));
	}
	
	/**
	 * Clears product cache after delete action
	 *
	 */
	protected function _afterDelete(){
		$this->_afterModify();
	}	
	
	/**
	 * Detects if attribute_id is set
	 *
	 */
	protected function _beforeModify(){
		if(!$this->_request->getParam('attribute_id')){
			$this->_messages->setMessage('Error! Attribute was not provided','error');
			$this->_redirect($this->_index_action);
		}
	}
}